/**
 * Copyright  2025, Hai Yue Xing He  ZHAO LIMIN
 *
 * @author        ZHAO LIMIN
 * @version       1.0.1
 * @since         2025-04
 *                数学工具类
 *
 * HYXHMathUtil.ts
 */
import { defaultValue } from './HYXHDefaultValue'
import { defined } from './Defined'
import { DeveloperError } from './DeveloperError'
import { MersenneTwister } from './MersenneTwister'
import { Check } from './Check'
export class HYXHMathUtil {
  /**
   * 0.1
   * @type {number}
   * @constant
   */
  public static readonly EPSILON1: number = 0.1
  /**
   * 0.01
   * @type {number}
   * @constant
   */
  public static readonly EPSILON2: number = 0.01
  /**
   * 0.001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON3: number = 0.001
  /**
   * 0.0001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON4: number = 0.0001
  /**
   * 0.00001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON5: number = 0.00001
  /**
   * 0.000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON6: number = 0.000001
  /**
   * 0.0000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON7: number = 0.0000001
  /**
   * 0.00000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON8: number = 0.00000001
  /**
   * 0.000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON9: number = 0.000000001
  /**
   * 0.0000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON10: number = 0.0000000001
  /**
   * 0.00000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON11: number = 0.00000000001
  /**
   * 0.000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON12: number = 0.000000000001
  /**
   * 0.0000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON13: number = 0.0000000000001
  /**
   * 0.00000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON14: number = 0.00000000000001
  /**
   * 0.000000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON15: number = 0.000000000000001
  /**
   * 0.0000000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON16: number = 0.0000000000000001
  /**
   * 0.00000000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON17: number = 0.00000000000000001
  /**
   * 0.000000000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON18: number = 0.000000000000000001
  /**
   * 0.0000000000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON19: number = 0.0000000000000000001
  /**
   * 0.00000000000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON20: number = 0.00000000000000000001
  /**
   * 0.000000000000000000001
   * @type {number}
   * @constant
   */
  public static readonly EPSILON21: number = 0.000000000000000000001
  /**
   * The gravitational parameter of the Earth in meters cubed
   * per second squared as defined by the WGS84 model: 3.986004418e14
   * @type {number}
   * @constant
   */
  public static readonly GRAVITATIONALPARAMETER: number = 3.986004418e14
  /**
   * Radius of the sun in meters: 6.955e8
   * @type {number}
   * @constant
   */
  public static readonly SOLAR_RADIUS: number = 6.955e8
  /**
   * The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
   * Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
   * Celestial Mechanics 82: 83-110, 2002.
   * @type {number}
   * @constant
   */
  public static readonly LUNAR_RADIUS: number = 1737400.0
  /**
   * 64 * 1024
   * @type {number}
   * @constant
   */
  public static readonly SIXTY_FOUR_KILOBYTES: number = 64 * 1024
  /**
   * 4 * 1024 * 1024 * 1024
   * @type {number}
   * @constant
   */
  public static readonly FOUR_GIGABYTES: number = 4 * 1024 * 1024 * 1024
  /**
   * Returns the sign of the value; 1 if the value is positive, -1 if the value is
   * negative, or 0 if the value is 0.
   *
   * @function
   * @param {number} value The value to return the sign of.
   * @returns {number} The sign of value.
   */
  public static sign(value: number): number {
    value = +value // coerce to number
    if (value === 0 || Number.isNaN(value)) {
      // zero or NaN
      return value
    }
    return value > 0 ? 1 : -1
  }
  /**
   * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
   * This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
   * 0.0 when the input value is 0.0.
   * @param {number} value The value to return the sign of.
   * @returns {number} The sign of value.
   */
  public static signNotZero(value: number): number {
    return value < 0.0 ? -1.0 : 1.0
  }
  /**
   * Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMaximum]
   * @param {number} value The scalar value in the range [-1.0, 1.0]
   * @param {number} [rangeMaximum=255] The maximum value in the mapped range, 255 by default.
   * @returns {number} A SNORM value, where 0 maps to -1.0 and rangeMaximum maps to 1.0.
   *
   * @see HYXHMathUtil.fromSNorm
   */
  public static toSNorm(value: number, rangeMaximum: number): number {
    const _rangeMaximum = defaultValue<number>(rangeMaximum, 255)
    return Math.round((HYXHMathUtil.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * _rangeMaximum)
  }

  /**
   * Converts a SNORM value in the range [0, rangeMaximum] to a scalar in the range [-1.0, 1.0].
   * @param {number} value SNORM value in the range [0, rangeMaximum]
   * @param {number} [rangeMaximum=255] The maximum value in the SNORM range, 255 by default.
   * @returns {number} Scalar in the range [-1.0, 1.0].
   *
   * @see HYXHMathUtil.toSNorm
   */
  public static fromSNorm(value: number, rangeMaximum: number): number {
    const _rangeMaximum = defaultValue(rangeMaximum, 255)
    return (HYXHMathUtil.clamp(value, 0.0, _rangeMaximum) / _rangeMaximum) * 2.0 - 1.0
  }

  /**
   * Converts a scalar value in the range [rangeMinimum, rangeMaximum] to a scalar in the range [0.0, 1.0]
   * @param {number} value The scalar value in the range [rangeMinimum, rangeMaximum]
   * @param {number} rangeMinimum The minimum value in the mapped range.
   * @param {number} rangeMaximum The maximum value in the mapped range.
   * @returns {number} A scalar value, where rangeMinimum maps to 0.0 and rangeMaximum maps to 1.0.
   */
  public static normalize (
    value: number,
    rangeMinimum: number,
    rangeMaximum: number,
  ): number {
    const _rangeMaximum = Math.max(rangeMaximum - rangeMinimum, 0.0)
    return _rangeMaximum === 0.0
      ? 0.0
      : HYXHMathUtil.clamp((value - _rangeMaximum) / _rangeMaximum, 0.0, 1.0)
  }

  /**
   * Returns the hyperbolic sine of a number.
   * The hyperbolic sine of <em>value</em> is defined to be
   * (<em>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></em>)/2.0
   * where <i>e</i> is Euler's number, approximately 2.71828183.
   *
   * <p>Special cases:
   *   <ul>
   *     <li>If the argument is NaN, then the result is NaN.</li>
   *
   *     <li>If the argument is infinite, then the result is an infinity
   *     with the same sign as the argument.</li>
   *
   *     <li>If the argument is zero, then the result is a zero with the
   *     same sign as the argument.</li>
   *   </ul>
   *</p>
   *
   * @function
   * @param {number} value The number whose hyperbolic sine is to be returned.
   * @returns {number} The hyperbolic sine of <code>value</code>.
   */
  public static readonly sinh = defaultValue(Math.sinh, function sinh(value) {
    return (Math.exp(value) - Math.exp(-value)) / 2.0
  })
  /**
   * Returns the hyperbolic cosine of a number.
   * The hyperbolic cosine of <strong>value</strong> is defined to be
   * (<em>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></em>)/2.0
   * where <i>e</i> is Euler's number, approximately 2.71828183.
   *
   * <p>Special cases:
   *   <ul>
   *     <li>If the argument is NaN, then the result is NaN.</li>
   *
   *     <li>If the argument is infinite, then the result is positive infinity.</li>
   *
   *     <li>If the argument is zero, then the result is 1.0.</li>
   *   </ul>
   *</p>
   *
   * @function
   * @param {number} value The number whose hyperbolic cosine is to be returned.
   * @returns {number} The hyperbolic cosine of <code>value</code>.
   */
  public static readonly cosh = defaultValue(Math.cosh, function cosh(value) {
    return (Math.exp(value) + Math.exp(-value)) / 2.0
  })

  /**
   * Computes the linear interpolation of two values.
   *
   * @param {number} p The start value to interpolate.
   * @param {number} q The end value to interpolate.
   * @param {number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
   * @returns {number} The linearly interpolated value.
   *
   * @example
   * const n = Math.lerp(0.0, 2.0, 0.5); // returns 1.0
   */
  public static lerp(p: number, q: number, time: number): number {
    return (1.0 - time) * p + time * q
  }

  /**
   * pi
   *
   * @type {number}
   * @constant
   */
  public static readonly PI: number = Math.PI

  /**
   * 1/pi
   *
   * @type {number}
   * @constant
   */
  public static readonly ONE_OVER_PI = 1.0 / Math.PI

  /**
   * pi/2
   *
   * @type {number}
   * @constant
   */
  public static readonly PI_OVER_TWO = Math.PI / 2.0

  /**
   * pi/3
   *
   * @type {number}
   * @constant
   */
  public static readonly PI_OVER_THREE = Math.PI / 3.0

  /**
   * pi/4
   *
   * @type {number}
   * @constant
   */
  public static readonly PI_OVER_FOUR = Math.PI / 4.0

  /**
   * pi/6
   *
   * @type {number}
   * @constant
   */
  public static readonly PI_OVER_SIX = Math.PI / 6.0

  /**
   * 3pi/2
   *
   * @type {number}
   * @constant
   */
  public static readonly THREE_PI_OVER_TWO = (3.0 * Math.PI) / 2.0

  /**
   * 2pi
   *
   * @type {number}
   * @constant
   */
  public static readonly TWO_PI = 2.0 * Math.PI

  /**
   * 1/2pi
   *
   * @type {number}
   * @constant
   */
  public static readonly ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI)

  /**
   * The number of radians in a degree.
   *
   * @type {number}
   * @constant
   */
  public static readonly RADIANS_PER_DEGREE = Math.PI / 180.0

  /**
   * The number of degrees in a radian.
   *
   * @type {number}
   * @constant
   */
  public static readonly DEGREES_PER_RADIAN = 180.0 / Math.PI

  /**
   * The number of radians in an arc second.
   *
   * @type {number}
   * @constant
   */
  public static readonly RADIANS_PER_ARCSECOND = HYXHMathUtil.RADIANS_PER_DEGREE / 3600.0

  /**
   * Converts degrees to radians.
   * @param {number} degrees The angle to convert in degrees.
   * @returns {number} The corresponding angle in radians.
   */
  public static toRadians(degrees: number): number {
    Check.typeOf.number('degrees', degrees)
    return degrees * HYXHMathUtil.RADIANS_PER_DEGREE
  }

  /**
   * Converts radians to degrees.
   * @param {number} radians The angle to convert in radians.
   * @returns {number} The corresponding angle in degrees.
   */
  public static toDegrees(radians: number): number {
    Check.typeOf.number('radians', radians)
    return radians * HYXHMathUtil.DEGREES_PER_RADIAN
  }

  /**
   * Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
   *
   * @param {number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
   * @returns {number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
   *
   * @example
   * // Convert 270 degrees to -90 degrees longitude
   * const longitude = Math.convertLongitudeRange(Math.toRadians(270.0));
   */
  public static convertLongitudeRange(angle: number): number {
    Check.typeOf.number('angle', angle)
    const twoPi = HYXHMathUtil.TWO_PI

    const simplified = angle - Math.floor(angle / twoPi) * twoPi

    if (simplified < -Math.PI) {
      return simplified + twoPi
    }
    if (simplified >= Math.PI) {
      return simplified - twoPi
    }

    return simplified
  }

  /**
   * Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
   * Useful for sanitizing data before use in objects requiring correct range.
   *
   * @param {number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
   * @returns {number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
   *
   * @example
   * // Clamp 108 degrees latitude to 90 degrees latitude
   * const latitude = Math.clampToLatitudeRange(Math.toRadians(108.0));
   */
  public static clampToLatitudeRange(angle: number): number {
    Check.typeOf.number('angle', angle)
    return HYXHMathUtil.clamp(angle, -1 * HYXHMathUtil.PI_OVER_TWO, HYXHMathUtil.PI_OVER_TWO)
  }

  /**
   * Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
   *
   * @param {number} angle in radians
   * @returns {number} The angle in the range [<code>-HYXHMathUtilPI</code>, <code>HYXHMathUtil.PI</code>].
   */
  public static negativePiToPi(angle: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('angle', angle)
    //>>includeEnd('debug');
    if (angle >= -HYXHMathUtil.PI && angle <= HYXHMathUtil.PI) {
      // Early exit if the input is already inside the range. This avoids
      // unnecessary math which could introduce floating point error.
      return angle
    }
    return HYXHMathUtil.zeroToTwoPi(angle + HYXHMathUtil.PI) - HYXHMathUtil.PI
  }

  /**
   * Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
   *
   * @param {number} angle in radians
   * @returns {number} The angle in the range [0, <code>HYXHMathUtil.TWO_PI</code>].
   */
  public static zeroToTwoPi(angle: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('angle', angle)
    //>>includeEnd('debug');
    if (angle >= 0 && angle <= HYXHMathUtil.TWO_PI) {
      // Early exit if the input is already inside the range. This avoids
      // unnecessary math which could introduce floating point error.
      return angle
    }
    const mod = HYXHMathUtil.mod(angle, HYXHMathUtil.TWO_PI)
    if (Math.abs(mod) < HYXHMathUtil.EPSILON14 && Math.abs(angle) > HYXHMathUtil.EPSILON14) {
      return HYXHMathUtil.TWO_PI
    }
    return mod
  }

  /**
   * The modulo operation that also works for negative dividends.
   *
   * @param {number} m The dividend.
   * @param {number} n The divisor.
   * @returns {number} The remainder.
   */
  public static mod(m: number, n: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('m', m)
    Check.typeOf.number('n', n)
    if (n === 0.0) {
      throw new DeveloperError('HYXHMathUtil.mod input parameter divisor cannot be 0.')
    }
    //>>includeEnd('debug');
    if (HYXHMathUtil.sign(m) === HYXHMathUtil.sign(n) && Math.abs(m) < Math.abs(n)) {
      // Early exit if the input does not need to be modded. This avoids
      // unnecessary math which could introduce floating point error.
      return m
    }

    return ((m % n) + n) % n
  }

  /**
   * Determines if two values are equal using an absolute or relative tolerance test. This is useful
   * to avoid problems due to roundoff error when comparing floating-point values directly. The values are
   * first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
   * Use this test if you are unsure of the magnitudes of left and right.
   *
   * @param {number} left The first value to compare.
   * @param {number} right The other value to compare.
   * @param {number} [relativeEpsilon=0] The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
   * @param {number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
   * @returns {boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
   *
   * @example
   * const a = Math.equalsEpsilon(0.0, 0.01, Math.EPSILON2); // true
   * const b = Math.equalsEpsilon(0.0, 0.1, Math.EPSILON2);  // false
   * const c = Math.equalsEpsilon(3699175.1634344, 3699175.2, Math.EPSILON7); // true
   * const d = Math.equalsEpsilon(3699175.1634344, 3699175.2, Math.EPSILON9); // false
   */
  public static equalsEpsilon(
    left: number,
    right: number,
    relativeEpsilon: number,
    absoluteEpsilon: number = relativeEpsilon,
  ): boolean {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('left', left)
    Check.typeOf.number('right', right)
    //>>includeEnd('debug');

    relativeEpsilon = defaultValue(relativeEpsilon, 0.0)
    absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon)
    const absDiff = Math.abs(left - right)
    return (
      absDiff <= absoluteEpsilon ||
      absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right))
    )
  }

  /**
   * Determines if the left value is less than the right value. If the two values are within
   * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns false.
   *
   * @param {number} left The first number to compare.
   * @param {number} right The second number to compare.
   * @param {number} absoluteEpsilon The absolute epsilon to use in comparison.
   * @returns {boolean} <code>true</code> if <code>left</code> is less than <code>right</code> by more than
   *          <code>absoluteEpsilon<code>. <code>false</code> if <code>left</code> is greater or if the two
   *          values are nearly equal.
   */
  public static lessThan(left: number, right: number, absoluteEpsilon: number): boolean {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('left', left)
    Check.typeOf.number('right', right)
    Check.typeOf.number('absoluteEpsilon', absoluteEpsilon)
    //>>includeEnd('debug');
    return left - right < -absoluteEpsilon
  }

  /**
   * Determines if the left value is less than or equal to the right value. If the two values are within
   * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns true.
   *
   * @param {number} left The first number to compare.
   * @param {number} right The second number to compare.
   * @param {number} absoluteEpsilon The absolute epsilon to use in comparison.
   * @returns {boolean} <code>true</code> if <code>left</code> is less than <code>right</code> or if the
   *          the values are nearly equal.
   */
  public static lessThanOrEquals(left: number, right: number, absoluteEpsilon: number): boolean {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('left', left)
    Check.typeOf.number('right', right)
    Check.typeOf.number('absoluteEpsilon', absoluteEpsilon)
    //>>includeEnd('debug');
    return left - right < absoluteEpsilon
  }

  /**
   * Determines if the left value is greater the right value. If the two values are within
   * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns false.
   *
   * @param {number} left The first number to compare.
   * @param {number} right The second number to compare.
   * @param {number} absoluteEpsilon The absolute epsilon to use in comparison.
   * @returns {boolean} <code>true</code> if <code>left</code> is greater than <code>right</code> by more than
   *          <code>absoluteEpsilon<code>. <code>false</code> if <code>left</code> is less or if the two
   *          values are nearly equal.
   */
  public static greaterThan(left: number, right: number, absoluteEpsilon: number): boolean {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('left', left)
    Check.typeOf.number('right', right)
    Check.typeOf.number('absoluteEpsilon', absoluteEpsilon)
    //>>includeEnd('debug');
    return left - right > absoluteEpsilon
  }

  /**
   * Determines if the left value is greater than or equal to the right value. If the two values are within
   * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns true.
   *
   * @param {number} left The first number to compare.
   * @param {number} right The second number to compare.
   * @param {number} absoluteEpsilon The absolute epsilon to use in comparison.
   * @returns {boolean} <code>true</code> if <code>left</code> is greater than <code>right</code> or if the
   *          the values are nearly equal.
   */
  public static greaterThanOrEquals(left: number, right: number, absoluteEpsilon: number): boolean {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('left', left)
    Check.typeOf.number('right', right)
    Check.typeOf.number('absoluteEpsilon', absoluteEpsilon)
    //>>includeEnd('debug');
    return left - right > -absoluteEpsilon
  }

  private static readonly factorials: Array<number> = [1]

  /**
   * Computes the factorial of the provided number.
   *
   * @param {number} n The number whose factorial is to be computed.
   * @returns {number} The factorial of the provided number or undefined if the number is less than 0.
   *
   * @exception {DeveloperError} A number greater than or equal to 0 is required.
   *
   *
   * @example
   * //Compute 7!, which is equal to 5040
   * const computedFactorial = Math.factorial(7);
   *
   */
  public static factorial(n: number): number {
    //if (typeof n !== 'number' || n < 0) {
    // if ( Check.number.checkTOutRange(n, 0)) {
    //   throw new DeveloperError(
    //     'HYXHMathUtil.factorial input parameter n: A number greater than or equal to 0 is required.',
    //   )
    // }
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.tnumber.checkTOutRange('n', n, 0)
    //>>includeEnd('debug');
    const _length = HYXHMathUtil.factorials.length
    if (n >= _length) {
      let sum = HYXHMathUtil.factorials[_length - 1]
      for (let i = _length; i <= n; i++) {
        const next = sum * i
        HYXHMathUtil.factorials.push(next)
        sum = next
      }
    }
    return HYXHMathUtil.factorials[n]
  }

  /**
   * Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
   *
   * @param {number} [n] The number to be incremented.
   * @param {number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
   * @param {number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
   * @returns {number} The incremented number.
   *
   * @exception {DeveloperError} Maximum value must be greater than minimum value.
   *
   * @example
   * const n = Math.incrementWrap(5, 10, 0); // returns 6
   * const m = Math.incrementWrap(10, 10, 0); // returns 0
   */
  public static incrementWrap(n: number, maximumValue: number, minimumValue: number): number {
    minimumValue = defaultValue(minimumValue, 0.0)
    // if (!Check.number.check(n)) {
    //   throw new DeveloperError('HYXHMathUtil.incrementWrap input parameter n is required.')
    // }
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('n', n)
    //>>includeEnd('debug');
    if (maximumValue <= minimumValue) {
      throw new DeveloperError(
        'HYXHMathUtil.incrementWrap input parameter maximumValue must be greater than minimumValue.',
      )
    }

    ++n
    if (n > maximumValue) {
      n = minimumValue
    }
    return n
  }

  /**
   * Determines if a non-negative integer is a power of two.
   * The maximum allowed input is (2^32)-1 due to 32-bit bitwise operator limitation in Javascript.
   *
   * @param {number} n The integer to test in the range [0, (2^32)-1].
   * @returns {boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
   *
   * @exception {DeveloperError} A number between 0 and (2^32)-1 is required.
   *
   * @example
   * const t = Math.isPowerOfTwo(16); // true
   * const f = Math.isPowerOfTwo(20); // false
   */
  public static isPowerOfTwo(n: number): boolean {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.tnumber.checkIntegerTOutRange('n', n, 0, 4294967295)
    //>>includeEnd('debug');
    return n !== 0 && (n & (n - 1)) === 0
  }

  /**
   * Computes the next power-of-two integer greater than or equal to the provided non-negative integer.
   * The maximum allowed input is 2^31 due to 32-bit bitwise operator limitation in Javascript.
   *
   * @param {number} n The integer to test in the range [0, 2^31].
   * @returns {number} The next power-of-two integer.
   *
   * @exception {DeveloperError} A number between 0 and 2^31 is required.
   *
   * @example
   * const n = Math.nextPowerOfTwo(29); // 32
   * const m = Math.nextPowerOfTwo(32); // 32
   */
  public static nextPowerOfTwo(n: number): number {
    //>>includeStart('debug', pragmas.debug);
    //if (typeof n !== 'number' || n < 0 || n > 2147483648) {
    // if (Check.number.checkIntegerTOutRange(n, 0, 2147483648)) {
    //   throw new DeveloperError(
    //     'HYXHMathUtil.nextPowerOfTwo input parameter n:A number between 0 and 2^31 is required.',
    //   )
    // }
    Check.typeOf.tnumber.checkIntegerTOutRange('n', n, 0, 2147483648)
    //>>includeEnd('debug');
    // From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
    --n
    n |= n >> 1
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    ++n
    return n
  }

  /**
   * Computes the previous power-of-two integer less than or equal to the provided non-negative integer.
   * The maximum allowed input is (2^32)-1 due to 32-bit bitwise operator limitation in Javascript.
   *
   * @param {number} n The integer to test in the range [0, (2^32)-1].
   * @returns {number} The previous power-of-two integer.
   *
   * @exception {DeveloperError} A number between 0 and (2^32)-1 is required.
   *
   * @example
   * const n = Math.previousPowerOfTwo(29); // 16
   * const m = Math.previousPowerOfTwo(32); // 32
   */
  public static previousPowerOfTwo(n: number): number {
    //>>includeStart('debug', pragmas.debug);
    //if (typeof n !== 'number' || n < 0 || n > 4294967295) {
    // if (Check.number.checkIntegerTOutRange(n, 0, 4294967295)) {
    //   throw new DeveloperError(
    //     'HYXHMathUtil.previousPowerOfTwo input parameter n:A number between 0 and (2^32)-1 is required.',
    //   )
    // }
    Check.typeOf.tnumber.checkIntegerTOutRange('n', n, 0, 4294967295)
    //>>includeEnd('debug');

    n |= n >> 1
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    n |= n >> 32

    // The previous bitwise operations implicitly convert to signed 32-bit. Use `>>>` to convert to unsigned
    n = (n >>> 0) - (n >>> 1)

    return n
  }

  /**
   * Constraint a value to lie between two values.
   *
   * @param {number} value The value to clamp.
   * @param {number} min The minimum value.
   * @param {number} max The maximum value.
   * @returns {number} The clamped value such that min <= result <= max.
   */
  public static clamp(value: number, min: number, max: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('value', value)
    Check.typeOf.number('min', min)
    Check.typeOf.number('max', max)
    //>>includeEnd('debug');
    return value < min ? min : value > max ? max : value
  }

  /* 梅森旋转算法 */
  private static randomNumberGenerator = new MersenneTwister()

  /**
   * Sets the seed used by the random number generator
   * in {@link CesiumMath#nextRandomNumber}.
   *
   * @param {number} seed An integer used as the seed.
   */
  public static setRandomNumberSeed(seed: number): void {
    // if (!Check.number.checkInteger(seed)) {
    //   throw new DeveloperError('HYXHMathUtil.setRandomNumberSeed input parameter seed is required.')
    // }
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.tnumber.checkInteger('seed', seed)
    //>>includeEnd('debug');
    if (!defined(HYXHMathUtil.randomNumberGenerator)) {
      HYXHMathUtil.randomNumberGenerator = new MersenneTwister(seed)
    } else {
      HYXHMathUtil.randomNumberGenerator.setSeed(seed)
    }
  }

  /**
   * Generates a random floating point number in the range of [0.0, 1.0)
   * using a Mersenne twister.
   *
   * @returns {number} A random number in the range of [0.0, 1.0).
   *
   * @see HYXHMathUtil.setRandomNumberSeed
   */
  public static nextRandomNumber(): number {
    return HYXHMathUtil.randomNumberGenerator.random()
  }

  /**
   * Generates a random number between two numbers.
   *
   * @param {number} min The minimum value.
   * @param {number} max The maximum value.
   * @returns {number} A random number between the min and max.
   */
  public static randomBetween(min: number, max: number): number {
    return HYXHMathUtil.nextRandomNumber() * (max - min) + min
  }

  /**
   * Computes <code>Math.acos(value)</code>, but first clamps <code>value</code> to the range [-1.0, 1.0]
   * so that the function will never return NaN.
   *
   * @param {number} value The value for which to compute acos.
   * @returns {number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
   *          whichever is closer, if the value is outside the range.
   */
  public static acosClamped(value: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('value', value)
    //>>includeEnd('debug');
    return Math.acos(HYXHMathUtil.clamp(value, -1.0, 1.0))
  }

  /**
   * Computes <code>Math.asin(value)</code>, but first clamps <code>value</code> to the range [-1.0, 1.0]
   * so that the function will never return NaN.
   *
   * @param {number} value The value for which to compute asin.
   * @returns {number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
   *          whichever is closer, if the value is outside the range.
   */
  public static asinClamped(value: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('value', value)
    //>>includeEnd('debug');
    return Math.asin(HYXHMathUtil.clamp(value, -1.0, 1.0))
  }

  /**
   * Finds the chord length between two points given the circle's radius and the angle between the points.
   *
   * @param {number} angle The angle between the two points.
   * @param {number} radius The radius of the circle.
   * @returns {number} The chord length.
   */
  public static chordLength(angle: number, radius: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('angle', angle)
    Check.typeOf.number('radius', radius)
    //>>includeEnd('debug');
    return 2.0 * radius * Math.sin(angle * 0.5)
  }

  /**
   * Finds the logarithm of a number to a base.
   *
   * @param {number} number The number.
   * @param {number} base The base.
   * @returns {number} The result.
   */
  public static logBase(number: number, base: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('number', number)
    Check.typeOf.number('base', base)
    //>>includeEnd('debug');
    return Math.log(number) / Math.log(base)
  }

  /**
   * Finds the cube root of a number.
   * Returns NaN if <code>number</code> is not provided.
   *
   * @function
   * @param {number} [number] The number.
   * @returns {number} The result.
   */
  public static readonly cbrt = defaultValue(Math.cbrt, function cbrt(number: number) {
    const result = Math.pow(Math.abs(number), 1.0 / 3.0)
    return number < 0.0 ? -result : result
  })

  /**
   * Finds the base 2 logarithm of a number.
   *
   * @function
   * @param {number} number The number.
   * @returns {number} The result.
   */
  public static readonly log2 = defaultValue(Math.log2, function log2(number) {
    return Math.log(number) * Math.LOG2E
  })

  /**
   * @private
   */
  public static fog(distanceToCamera: number, density: number): number {
    const scalar = distanceToCamera * density
    return 1.0 - Math.exp(-(scalar * scalar))
  }

  /**
   * Computes a fast approximation of Atan for input in the range [-1, 1].
   *
   * Based on Michal Drobot's approximation from ShaderFastLibs,
   * which in turn is based on "Efficient approximations for the arctangent function,"
   * Rajan, S. Sichun Wang Inkol, R. Joyal, A., May 2006.
   * Adapted from ShaderFastLibs under MIT License.
   *
   * @param {number} x An input number in the range [-1, 1]
   * @returns {number} An approximation of atan(x)
   */
  public static fastApproximateAtan(x: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.tnumber.checkRange('x', x, -1.0, 1.0)
    //>>includeEnd('debug');
    return x * (-0.1784 * Math.abs(x) - 0.0663 * x * x + 1.0301)
  }

  /**
   * Computes a fast approximation of Atan2(x, y) for arbitrary input scalars.
   *
   * Range reduction math based on nvidia's cg reference implementation: http://developer.download.nvidia.com/cg/atan2.html
   *
   * @param {number} x An input number that isn't zero if y is zero.
   * @param {number} y An input number that isn't zero if x is zero.
   * @returns {number} An approximation of atan2(x, y)
   */
  public static fastApproximateAtan2(x: number, y: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('x', x)
    Check.typeOf.number('y', y)
    //>>includeEnd('debug');
    // atan approximations are usually only reliable over [-1, 1]
    // So reduce the range by flipping whether x or y is on top based on which is bigger.
    let opposite
    let t = Math.abs(x) // t used as swap and atan result.
    opposite = Math.abs(y)
    const adjacent = Math.max(t, opposite)
    opposite = Math.min(t, opposite)

    const oppositeOverAdjacent = opposite / adjacent
    //>>includeStart('debug', pragmas.debug);
    if (isNaN(oppositeOverAdjacent)) {
      throw new DeveloperError(
        'HYXHMathUtil.fastApproximateAtan2 input parameter either x or y must be nonzero',
      )
    }
    //>>includeEnd('debug');
    t = HYXHMathUtil.fastApproximateAtan(oppositeOverAdjacent)

    // Undo range reduction
    t = Math.abs(y) > Math.abs(x) ? HYXHMathUtil.PI_OVER_TWO - t : t
    t = x < 0.0 ? HYXHMathUtil.PI - t : t
    t = y < 0.0 ? -t : t
    return t
  }
}
